const User = require('../models/User')
const mongoose = require('mongoose')
const utils = require('../utils/index')
// 响应的json数据
const responseData = {
  code: 200,
  msg: 'success',
  data: {}
}

// 检查用户是否存在
exports.check = (req, res, next) => {
  const _id = req.body.uid || ''
  if(!_id) {
    responseData.code = 500
    responseData.msg = '用户id不能为空'
    responseData.data = {}
    return res.json(responseData)
  }
  if(!mongoose.Types.ObjectId.isValid(_id)) {
    responseData.code = 500
    responseData.msg = '用户id不是有效的类型'
    responseData.data = {}
    return res.json(responseData)
  }
  if(!utils.checkObjecID(_id)) {
    responseData.code = 500
    responseData.msg = '用户id不合法'
    responseData.data = {}
    return res.json(responseData)
  }
  User.findOne({
    _id: mongoose.Types.ObjectId(_id)
  }).then(userInfo => {
    if(userInfo) {
      next()
    } else {
      responseData.code = 500
      responseData.msg = '此用户不存在'
      responseData.data = {}
      return res.json(responseData)
    }
  }).catch(err => {
    responseData.code = 500
    responseData.msg = '应用出现异常'
    responseData.data = {}
    return res.json(responseData)
  })
}
